package com.zfl;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Codec {

    private static final String nullStr = "null,";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        this.serializeHelper(root,sb);
        return sb.toString();
    }

    private void serializeHelper(TreeNode root, StringBuilder sb) {
        if(root==null) {
            sb.append(nullStr);
            return;
        }
        sb.append(root.val).append(",");
        serializeHelper(root.left,sb);
        serializeHelper(root.right,sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Queue<String> nodes = new LinkedList<>(Arrays.asList(data.split(",")));
        TreeNode node = this.deserializeHelper(nodes);
        return node;
    }

    private TreeNode deserializeHelper(Queue<String> nodes) {
        String val = nodes.poll();
        if("null".equals(val))
            return null;
        TreeNode node = new TreeNode(Integer.parseInt(val));
        node.left = this.deserializeHelper(nodes);
        node.right = this.deserializeHelper(nodes);
        return node;
    }
}
